<?php

namespace App\Jobs;

use Carbon\Carbon;
use App\Models\Video;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Darabonba\OpenApi\OpenApiClient;
use AlibabaCloud\OpenApiUtil\OpenApiUtilClient;

use Darabonba\OpenApi\Models\Config;
use Darabonba\OpenApi\Models\Params;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use Darabonba\OpenApi\Models\OpenApiRequest;

class VideoTranslateJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
	
	/**
	 * @var User
	 */
    protected $video = null;
    
    public function __construct(Video $video = null)
    {
        $this->video = $video;
        $this->delay(Carbon::now()->addMinutes(5));
    }

     public static function createClient(){
        // 工程代码泄露可能会导致 AccessKey 泄露，并威胁账号下所有资源的安全性。以下代码示例仅供参考。
        // 建议使用更安全的 STS 方式，更多鉴权访问方式请参见：https://help.aliyun.com/document_detail/311677.html。
        $config = new Config([
            // 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID。
            "accessKeyId" => env("ALIYUN_TINGWU_ACCESS_KEY_ID"),
            // 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
            "accessKeySecret" => env("ALIYUN_TINGWU_ACCESS_KEY_SECRET")
        ]);
        // Endpoint 请参考 https://api.aliyun.com/product/tingwu
        $config->endpoint = "tingwu.cn-beijing.aliyuncs.com";
        return new OpenApiClient($config);
    }

    /**
     * API 相关
     * @return Params OpenApi.Params
     */
    public static function createApiInfo($taskId){

         $params = new Params([
            // 接口名称
            "action" => "GetTaskInfo",
            // 接口版本
            "version" => "2023-09-30",
            // 接口协议
            "protocol" => "HTTPS",
            // 接口 HTTP 方法
            "method" => "GET",
            "authType" => "AK",
            "style" => "ROA",
            // 接口 PATH
            "pathname" => "/openapi/tingwu/v2/tasks/". $taskId,
            // 接口请求体内容格式
            "reqBodyType" => "json",
            // 接口响应体内容格式
            "bodyType" => "json"
        ]);
        return $params;
    }

    /**
     * @param string[] $args
     * @return void
     */
    public function main(){
         $client = self::createClient();
        $params = self::createApiInfo($this->video->task_id);
        // runtime options
        $runtime = new RuntimeOptions([]);
        $request = new OpenApiRequest([]);
        // 复制代码运行请自行打印 API 的返回值

        // 返回值实际为 Map 类型，可从 Map 中获得三类数据：响应体 body、响应头 headers、HTTP 返回的状态码 statusCode。
        $res = $client->callApi($params, $request, $runtime);
        
        
        if($res['body']['Data']['TaskStatus'] == "FAILED" || $res['body']['Data']['TaskStatus'] == "ONGOING"){

        	return false;
        }elseif($res['body']['Data']['TaskStatus'] == "COMPLETED"){

        	$translateJsonUrl = $res['body']['Data']['Result']['Translation'];
        	$translateJson = file_get_contents($translateJsonUrl);
        	$translateArr = json_decode($translateJson,true);

        	$content ="";
        	$brief ="";
        	if(isset($translateArr['Translation']['Paragraphs'])){
        		foreach($translateArr['Translation']['Paragraphs'] as $v){

        			if(!empty($v['Sentences'])){

        				foreach($v['Sentences'] as $sv){

        					$content.="<p>".$sv['Text']."</p>";
        				}
        			}
        			
        		}

        	}

        	$briefJsonUrl = $res['body']['Data']['Result']['Summarization'];
        	$briefJson = file_get_contents($briefJsonUrl);
        	$briefArr = json_decode($briefJson,true);

        	if($briefArr['Summarization']){

        		$brief = $briefArr['Summarization']['ParagraphSummary'];
        	}

        	$this->video->update(['content'=>$content,"brief"=>$brief]);

        }
    }
    
    public function handle()
    {

	  	$this->main();
    }
}
